package com.voyager.trip.system.controller;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.voyager.trip.common.result.JsonResult;
import com.voyager.trip.common.result.PageResult;
import com.voyager.trip.common.web.BaseController;
import com.voyager.trip.system.entity.SysUser;
import com.voyager.trip.system.service.UserService;

@RestController
@RequestMapping("/sys/user")
public class UserController extends BaseController {

	@Autowired
	private UserService userService;
	
	@GetMapping("/cur")
    public JsonResult userInfo() {
		SysUser curUser = getLoginUser();
		curUser.setPassword("");
        return JsonResult.ok().put("user", curUser);
    }
	
	@GetMapping("/list")
	public PageResult<SysUser> pageList(Integer page, Integer limit, String searchKey, String searchValue) {
		return userService.getPageList(page, limit, searchKey, searchValue);
	}
	
	@GetMapping("/{id}")
	public JsonResult query(@PathVariable String id) {
		SysUser user = userService.getUserById(id);
		return JsonResult.ok("get user success").put("user", user);
	}
	
	@PostMapping("/add")
	public JsonResult add(SysUser sysUser) {
		sysUser.setCreateUser(super.getLoginUser().getAccount());
		sysUser.setUpdateUser(super.getLoginUser().getAccount());
		return userService.addUser(sysUser);
	}
	
	@PostMapping("/edit")
	public JsonResult edit(SysUser sysUser) {
		sysUser.setUpdateUser(super.getLoginUser().getAccount());
		return userService.editUser(sysUser);
	}
	
	@DeleteMapping("/{id}")
	public JsonResult del(@PathVariable String id) {
		return userService.delUser(id);
	}
	
	@PostMapping("/editPwd")
	public JsonResult modifyPassword(String oldPsw, String newPsw) {
//		String finalSecret = "{bcrypt}" + new BCryptPasswordEncoder().matches(rawPassword, encodedPassword)encode(oldPsw);
        if (!new BCryptPasswordEncoder().matches(oldPsw, getLoginUser().getPassword().replace("{bcrypt}", ""))) {
            return JsonResult.error("your original password is incorrect");
        }
		return userService.modifyPassword(super.getLoginUserId(), newPsw);
	}
	
	@PostMapping("/resetPwd/{id}")
	public JsonResult resetPwd(@PathVariable String id) {
		return userService.resetPassword(id);
	}
}
